package com.example.administrator.szb.fragments.fragment_forWD;

import android.content.Intent;
import android.graphics.Color;
import android.graphics.drawable.GradientDrawable;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.android.volley.Request;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.bumptech.glide.Glide;
import com.example.administrator.szb.R;
import com.example.administrator.szb.activity.JSWebViewActivity;
import com.example.administrator.szb.activity.WTContentActivity;
import com.example.administrator.szb.adapter.BaseAdapter;
import com.example.administrator.szb.fragments.base.BaseFragment;
import com.example.administrator.szb.bean.WDListBean;
import com.example.administrator.szb.tinkerutil.SampleApplicationLike;
import com.example.administrator.szb.fragments.fragment_forTab.FragmentMessage;
import com.example.administrator.szb.http.HttpUtil;
import com.example.administrator.szb.http.URLAddress;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.api.OnRefreshLoadmoreListener;

import java.util.ArrayList;
import java.util.HashMap;

import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;

/**
 * Created by D N on 2017/9/20.
 */

public class FragmentWDWTType extends BaseFragment {
    View view;
    @Bind(R.id.wd_recyclerview)
    RecyclerView wdRecyclerview;
    @Bind(R.id.wd_swiperefreshlayout)
    SmartRefreshLayout wdSwiperefreshlayout;

    View headview, footerview;//recyclerview 中加入头部和尾部

    @Bind(R.id.wd_text_info)
    TextView wdTextInfo;
    @Bind(R.id.wd_image_info)
    ImageView wdImageInfo;
    @Bind(R.id.wd_ll_info)
    LinearLayout wdLlInfo;
    private ArrayList<WDListBean.DataBean.ListBean> mdata = new ArrayList<>();
    private BaseAdapter<WDListBean.DataBean.ListBean> adpter;

    int wz = 0;

    private int current_page = 1;//列表当前页
    private int per_page = 10;//默认展示条数

    private int type = 1;//表示问题类型，热门问题，还是最新问题
    private int business_id = 0;//表示业务标签

    View error_head;

    HashMap<String,String> business_map = new HashMap<>();
    private boolean isFirstEnter = true;

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        view = inflater.inflate(R.layout.fragment_for_wt_type, container, false);
        ButterKnife.bind(this, view);
        headview = LayoutInflater.from(getActivity()).inflate(R.layout.view_wd_headview, null);
        footerview = LayoutInflater.from(getActivity()).inflate(R.layout.view_wd_footer, null);
        footerview.setVisibility(View.INVISIBLE);
        initView();
        return view;
    }

    private void initView() {
        //initTabLayout();
        business_id = getArguments().getInt("business_id");
        type = getArguments().getInt("type");
        initRefreshLayout();


        if (business_id == 0) {
            wdLlInfo.setVisibility(View.GONE);
            headview.setVisibility(View.VISIBLE);
        }else{
            headview.setVisibility(View.GONE);
            wdLlInfo.setVisibility(View.VISIBLE);
            //wdTextInfo.setText(WecomeActivity.businessMap.get(business_id+""));

            //FragmentMessage.businessBean


            for (int i = 0; i < FragmentMessage.businessBean.getData().size(); i++) {
                business_map.put(""+ FragmentMessage.businessBean.getData().get(i).getId(),FragmentMessage.businessBean.getData().get(i).getTitle());
            }
            wdTextInfo.setText(business_map.get(business_id+"")+"的简介");

            wdLlInfo.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    Intent intent = new Intent(getActivity(),JSWebViewActivity.class);
                    intent.putExtra("title",business_map.get(business_id+""));
                    intent.putExtra("id",business_id);
                    startActivity(intent);
                }
            });
            wdImageInfo.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    wdLlInfo.setVisibility(View.GONE);
                }
            });
        }
    }

    /**
     * 开启刷新监听
     */
    private void initRefreshLayout() {
        //wdSwiperefreshlayout.setColorSchemeResources(R.color.zhutise);
//        wdSwiperefreshlayout.post(new Runnable() {
//            @Override
//            public void run() {
//                current_page = 1;
//                wdSwiperefreshlayout.setRefreshing(true);
//                requestReferList(business_id, type, 0);
//            }
//        });
//
//        wdSwiperefreshlayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
//            @Override
//            public void onRefresh() {
//                current_page = 1;
//                wdSwiperefreshlayout.setRefreshing(true);
//                requestReferList(business_id, type, 0);
//            }
//        });
//第一次进入演示刷新
        if (isFirstEnter) {
            isFirstEnter = false;
            wdSwiperefreshlayout.autoRefresh();
        }
        wdSwiperefreshlayout.setEnableLoadMore(true);//是否启用上拉加载功能
        wdSwiperefreshlayout.setEnableLoadMoreWhenContentNotFull(true);//是否在列表不满一页时候开启上拉加载功能


        wdSwiperefreshlayout.setOnRefreshLoadmoreListener(new OnRefreshLoadmoreListener() {
            @Override
            public void onLoadmore(RefreshLayout refreshlayout) {
                //refreshlayout.setLoadmoreFinished(false);//恢复上拉状态
               // Toasts.show(getActivity(), "加载更多啊", Toast.LENGTH_SHORT);
                requestReferList(business_id, type, 1);
            }

            @Override
            public void onRefresh(RefreshLayout refreshlayout) {
                current_page = 1;
                requestReferList(business_id, type, 0);
                //refreshlayout.finishRefresh();
            }
        });
    }

    /**
     * 执行业务请求
     * isRefreshOrMore :其中传入0代表刷新，1代表加载更多
     */
    private void requestReferList(int business_id, int type, final int isRefreshOrMore) {
        HashMap<String, String> map = new HashMap<>();
        map.put("code", HttpUtil.getParam());
        map.put("id", SampleApplicationLike.getUserloginInstance().getId() + "");
        map.put("business_id", business_id + "");
        map.put("type", type + "");
        map.put("current_page", current_page + "");
        map.put("per_page", per_page + "");
        HttpUtil.RequestGsonPost(SampleApplicationLike.getQueueInstance(), Request.Method.POST, WDListBean.class, URLAddress.URLBASE + URLAddress.URL_WD, map, new Response.Listener() {
            @Override
            public void onResponse(Object response) {
                //response.toString();
                WDListBean wdListbean = (WDListBean) response;
                if (wdListbean.getResult() == 1) {
                    if (isRefreshOrMore == 0) {

                        mdata.clear();
                        mdata.addAll(wdListbean.getData().getList());
                        wdSwiperefreshlayout.finishRefresh();
                        current_page = Integer.parseInt(wdListbean.getData().getCurrent_page()) + 1;
                        initRecyclerview();
                        // Toasts.show(getActivity(), "刷新成功", Toast.LENGTH_SHORT);
                    } else if (isRefreshOrMore == 1) {
                        if (wdListbean.getData().getList().size() > 0) {
                            current_page = Integer.parseInt(wdListbean.getData().getCurrent_page()) + 1;
                            mdata.addAll(wdListbean.getData().getList());
                        } else {
                            //Toasts.show(getActivity(), "没有数据了", Toast.LENGTH_SHORT);
                        }

                        wdSwiperefreshlayout.finishLoadmore(true);//结束加载（加载失败）
                        //wdSwiperefreshlayout.setLoadmoreFinished(true);//恢复上拉状态
                    }
                    adpter.notifyDataSetChanged();
                }
            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                error.toString();
            }
        });
    }

    /**
     * 初始化列表
     */
    private void initRecyclerview() {

        requestListData();
        if (business_id == 0){
            adpter.addHeaderView(headview);
            wz = 1;
        }
        wdRecyclerview.setLayoutManager(new LinearLayoutManager(getActivity()));
        if (mdata.size() == 0){
            error_head = LayoutInflater.from(getActivity()).inflate(R.layout.view_item_error, wdRecyclerview, false);
            String info = "";
            switch (type){
                case 1:
                    info = "暂无热门问题";
                    break;
                case 2:
                    info = "暂无最新问题";
                    break;
                case 3:
                    info = "暂无待回答问题";
                    break;
            }

            ((TextView)error_head.findViewById(R.id.text_view_error)).setText(""+info);
            adpter.addHeaderView(error_head);
        }else{
            //adpter.addFootView(footerview);
            //loadMore();//开启加载更多监听
        }



        wdRecyclerview.setAdapter(adpter);

    }

//    /**
//     * 开启加载更多
//     */
//    private void loadMore() {
//
//        wdRecyclerview.addOnScrollListener(new MyOnScroll() {
//            @Override
//            public void scrollBottom() {
//                if (!wdSwiperefreshlayout.isRefreshing()) {//如果在刷新状态就不再加载更多了！否则会触发两次srollBottom()方法！
//                    super.scrollBottom();
//                    footerview.setVisibility(View.VISIBLE);
//                    requestReferList(business_id, type, 1);
//                }
//
//            }
//        });
//    }

    /**
     * 请求列表数据
     */
    private void requestListData() {
        initAdapter();
    }

    /**
     * 初始化recyclerview的adapter
     */

    private void initAdapter() {

        adpter = new BaseAdapter<WDListBean.DataBean.ListBean>(getActivity(), mdata) {
            @Override
            public void convert(int position, BaseViewHolder holder, WDListBean.DataBean.ListBean resultMessage) {
                initItemData(holder, resultMessage);//填充列表数据
            }

            @Override
            public int getLayoutId(int viewType) {
                return R.layout.message_item;
            }
        };
        /**
         * 添砖到问题详情，回答问题
         */
        adpter.setOnItemClickListener(new BaseAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(View view, int position) {
                Intent intent = new Intent(getActivity(), WTContentActivity.class);
                //SampleApplicationLike.getQueueInstance().cancelAll("tag");
                intent.putExtra("refer_id", mdata.get(position - wz).getId());
                startActivity(intent);
            }
        });

    }

    /**
     * 将请求到的数据填充进列表的item
     *
     * @param holder
     * @param resultMessage
     */
    private void initItemData(BaseAdapter<WDListBean.DataBean.ListBean>.BaseViewHolder holder, WDListBean.DataBean.ListBean resultMessage) {
        GradientDrawable drawable;
        if (resultMessage != null) {
            ((TextView) holder.getView(R.id.textView_item)).setText(resultMessage.getName());
            if (resultMessage.getHeadimg() != null) {
                Glide.with(getActivity()).load(resultMessage.getHeadimg()).error(R.drawable.mrtx).into((ImageView) holder.getView(R.id.imageView_item));
            }
            ((TextView) holder.getView(R.id.time_item)).setText(resultMessage.getCreate_time());

            /**
             * 这里主要是动态显示用户的标签，方法比较笨，有待改进
             */
            if (resultMessage.getBusiness().size() > 0) {
                try {
                    if (resultMessage.getBusiness().get(0) != null) {
                        ((TextView) holder.getView(R.id.gpzy)).setVisibility(View.VISIBLE);
                        ((TextView) holder.getView(R.id.gpzy)).setText(resultMessage.getBusiness().get(0).getTitle());

                        //改变drawable的背景填充色
                        String color = resultMessage.getBusiness().get(0).getFont_color();
                        drawable = (GradientDrawable) ((TextView) holder.getView(R.id.gpzy)).getBackground();
                        drawable.setColor(Color.parseColor(resultMessage.getBusiness().get(0).getFont_color()));
                    }
                    if (resultMessage.getBusiness().get(1) != null) {
                        ((TextView) holder.getView(R.id.dzjc)).setVisibility(View.VISIBLE);
                        ((TextView) holder.getView(R.id.dzjc)).setText(resultMessage.getBusiness().get(1).getTitle());

                        //改变drawable的背景填充色
                        String color = resultMessage.getBusiness().get(1).getFont_color();
                        drawable = (GradientDrawable) ((TextView) holder.getView(R.id.dzjc)).getBackground();
                        drawable.setColor(Color.parseColor(resultMessage.getBusiness().get(1).getFont_color()));
                    }
                    if (resultMessage.getBusiness().get(2) != null) {
                        ((TextView) holder.getView(R.id.qylc)).setVisibility(View.VISIBLE);
                        ((TextView) holder.getView(R.id.qylc)).setText(resultMessage.getBusiness().get(2).getTitle());

                        //改变drawable的背景填充色
                        String color = resultMessage.getBusiness().get(2).getFont_color();
                        drawable = (GradientDrawable) ((TextView) holder.getView(R.id.qylc)).getBackground();
                        drawable.setColor(Color.parseColor(resultMessage.getBusiness().get(2).getFont_color()));
                    }
                    if (resultMessage.getBusiness().get(3) != null) {
                        ((TextView) holder.getView(R.id.gqdr)).setVisibility(View.VISIBLE);
                        ((TextView) holder.getView(R.id.gqdr)).setText(resultMessage.getBusiness().get(3).getTitle());

                        //改变drawable的背景填充色
                        String color = resultMessage.getBusiness().get(3).getFont_color();
                        drawable = (GradientDrawable) ((TextView) holder.getView(R.id.gqdr)).getBackground();
                        drawable.setColor(Color.parseColor(resultMessage.getBusiness().get(3).getFont_color()));
                    }
                } catch (Exception e) {
                    e.toString();
                }
            }

            ((TextView) holder.getView(R.id.title_item)).setText(resultMessage.getTitle());
            ((TextView) holder.getView(R.id.js_item)).setText(resultMessage.getContent());
            ((TextView) holder.getView(R.id.sc_item)).setText(resultMessage.getCollect_count() + "收藏");
            ((TextView) holder.getView(R.id.hd_item)).setText(resultMessage.getAnswer_count() + "回答");

        }
    }




    @Override
    public void onDestroyView() {
        super.onDestroyView();
        ButterKnife.unbind(this);
    }

    @OnClick(R.id.wd_image_info)
    public void onViewClicked() {
    }


}
